package com.atguigu.gmall.common.util;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Jsons {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toStr(Object object){

        String json = null;
        try {
            json = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("对象{}， json转换异常：{}",object,e);
        }
        return json;
    }

    public static<T> T toObj(String jsonStr,TypeReference<T> tf){
        if(RedisConst.TEMP_DATA.equals(jsonStr)){
            return null;
        }
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            log.error("json字符串{}， 转对象异常：{}",jsonStr,e);
        }
        return t;
    }

    public static<T> T toObj(String jsonStr,Class<T> tf){
        if(RedisConst.TEMP_DATA.equals(jsonStr)){
            //如果redis缓存的是临时占位符，就创建一个空对象返回出去
//            T t = null;
//            try {
//                t = tf.newInstance();
//            } catch (InstantiationException e) {
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//            return t;
            throw new GmallException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            log.error("json字符串{}， 转对象异常：{}",jsonStr,e);
        }
        return t;
    }
}
